package sort;

import java.util.Arrays;

/**
 * @author wcj
 * @Date 2021/7/7 1:37
 * @Version 1.0
 */
public class HeapSort {

    public static void heapSort(int[] arr) {
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            heapAdjust(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            swap(arr, 0, i);
            heapAdjust(arr, 0, i);
        }
    }

    public static void heapAdjust(int[] arr, int i, int L) {
        int tmp = arr[i];
        for (int j = 2 * i + 1; j < L; j = j * 2 + 1) {
            if (j + 1 < L && arr[j] < arr[j + 1]) {
                j++;
            }
            if (tmp > arr[j]) {
                break;
            }
            arr[i] = arr[j];
            i = j;
        }
        arr[i] = tmp;
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
